/*
 *  Clase para hacer llamadas ajax
 *  *************************************************************************************************************************
 **/

function Request(){}

Request.prototype.request = function(config){
    jQuery.ajax({
        url: config.url,
        data:config.data,
        type:'POST',
        success: function(data) {
            if(data!==null){
                if(data.success){
                    if(config.success){
                        config.success(data);
                    }
                    else console.log('Error , debe definir callback de success en llamada Request');
                }
            }
        },
        error:function(data){
            console.log('Request status call:error ')
            if(config.error){
                config.error(data);
            }
        },
        dataFilter:function(dataType){
            
            /*console.log('Request status call:dataFilter ')
            if(config.dataFilter){
                config.dataFilter(dataType);
            }
            else{
                
                console.debug(dataType);
                
                if(dataType.lenght !== 0 && !jQuery.isEmptyObject(dataType) ){
                    dataType = jQuery.parseJSON( dataType )
                }
                else{
                    console.log("sin datos validos");
                    dataType=null;
                } 
                return dataType;
            }*/
            return dataType;
        }
    });
};

/*
 *  Clase para hacer definir modelos usados por los Store's
 *  *************************************************************************************************************************
 **/

function Model(cfg){
    this.definition = cfg;
    var _this = this;
    this._init = function(){
        $.each(this.definition,function(index,value){
            _this[index] =value;
        });
    };
    this.get = function(index){
        var res = '';
        return this.definition[index];
    }
    this.set = function(val){
        return;
    }
    return this;
}

/*
 *  Clase core
 *  *************************************************************************************************************************
 **/


function core(){
    
}

core.prototype.beautyForms = true;
core.prototype.id = '';
core.prototype.isCreated = false;
/*
 * Define si se usara el plugin para homogenizar los formularios y sus elementos
 */
core.prototype.setBeautyForms = function(beauty){
    this.beautyForms = beauty;
}
/*
 * Retorna TRUE/FALSE en caso de que se este usando beautyForms
 */
core.prototype.getBeautyForms = function(){
    return this.beautyForms;
}
/*
 * Return: String ID Ejem: '#mi_id'
 */
core.prototype.getId = function(textid){
    return "#"+textid;
}
/*
 * Create unique ID
 */
core.prototype.uniqueId = function(){
    var rand = Math.floor(Math.random() * 2000);
    return "Rocket-"+rand+""+(new Date()).getTime();
}
core.prototype.is_empty = function(val){
    if(val.lenght === 0 || jQuery.isEmptyObject(val) || val==="")
        return true;
    else return false;
};
core.prototype.setIdToForm = function(data,id){
    var i=data.indexOf('<form');
    if(i!=-1){//el formulario existe en la variable de texto
        var idText = '<form id="'+id+'" ';
        
        // console.log(idText);
        
        data = idText+' '+data.substring(5, data.length);
    }
    return data;
}

/*
 *  Clase Rocket de la cual proceden todos los modelos y metodos
 *  *************************************************************************************************************************
 **/


Rocket = new core();

/*
 *  Clase para crear elementos on the fly
 *  *************************************************************************************************************************
 **/


Element.prototype = new core();
Element.prototype.constructor = Element;

function Element(){}

Element.prototype.value = '';
Element.prototype.id = '';
Element.prototype.type='';
Element.prototype.renderTo='';
Element.prototype.name='';
Element.prototype.label='';
Element.prototype.width = '';
Element.prototype.height = '';
Element.prototype.fields = [];

Element.prototype.show = false;

Element.prototype.rendered = false;

Element.prototype.proxy = [];

Element.prototype.change = {};
Element.prototype.indexList = -1;
Element.prototype.dataIndex = '';
Element.prototype.dataField = '';
Element.prototype.modelItems = [];


Element.prototype.store = {};

Element.prototype.formatSizeStyle = function(size){
    var res_size= size;
    if(size.indexOf('%')=="-1" && size.indexOf('px')=="-1"){
        res_size = size+'px';
    }
    return res_size;
}


Element.prototype.setWidth = function(width){
    this.width = width;
    var eid = this.getId(this.id);
    switch(this.type){
        case 'text':
            eid = $(eid).parent().parent().parent();
            break;
        case "select":
            eid = $(eid).next();
        break;
        case 'panel':
            eid = this.getId(this.renderTo);
            eid = $(eid).parent().parent();
        break;
    }
    
    width = this.formatSizeStyle(width);
    $(eid).css('width',width);
};




Element.prototype.setHeight = function(height){
    this.height = height;
    var eid = this.getId(this.id);
    switch(this.type){
        case 'text':
            eid = $(eid).parent().parent().parent();
            break;
        case "select":
            eid = $(eid).next();
        break;
        case 'panel':
            eid = this.getId(this.renderTo);
            eid = $(eid).parent().parent();
        break;
    }
    height = this.formatSizeStyle(height);
    $(eid).css('height',height);
};



Element.prototype.setRenderTo = function(render){
    if(render!==''){
        this.renderTo = render;
    }
};
Element.prototype.render = function(){
    if(!this.rendered){
        var eid = this.getId(this.renderTo);
        this.create(this);
    }
};
Element.prototype.getWidth = function(){
    return this.width;
};
Element.prototype.getHeight = function(){
    return this.height;
};


Element.prototype.addClickEvents= function(){
    var eid = this.getId(this.id);
    var _this = this;
    $(eid).click(function(){
        if(_this.handler){
            _this.handler();
        }
    });
};
Element.prototype.addSelectEvents= function(){
    var eid = this.getId(this.id);
    var self = this;
    $(eid).change(function(a,b) {
        var modelId = $(eid).attr('idSelected');
        var record = self.modelItems[modelId].row;
        self.change(record, self);
    });
};

Element.prototype.getSelectedItem= function(){
    var eid = this.getId(this.id);
    var modelId = $(eid).attr('idSelected');
    if(!this.is_empty(modelId))
        return this.modelItems[modelId].row;
    else return this.modelItems[0].row;
};

Element.prototype.getButtonString = function(){
    return '<input id="'+this.id+'" name="'+this.name+'" value="'+this.value+'" type="button"/>';
};
Element.prototype.getTextInputString = function(){
    return '<input id="'+this.id+'" name="'+this.name+'" value="'+this.value+'" type="text"/>';
};
Element.prototype.getLabelStringFor = function(){
    return '<label class="rck_panel_label" for="'+this.name+'">'+this.label+'</label>';
};
Element.prototype.getLabelString = function(){
    return '<label>'+this.label+'</label>';
};
Element.prototype.getSelectString = function(){
    var sel = '<select name="'+this.name+'" id="'+this.id+'" textSelected="" idSelected="">';
    var selEnd = '</select>';
    var selId = this.getId(this.id);
    var options = '';
    var _this = this;
    
    if(_this.indexList<0) _this.indexList++;
    i = _this.indexList;
    jQuery.each(this.fields, function(index,item){
        value = item[_this.dataIndex];
        text = item[_this.dataField];
        options = options+'<option idList="'+i+'" value="'+value+'">'+text+'</option>';
        _this.modelItems[i] = {
            i:i, 
            row:new Model(item)
        };
        i++;
    });
    _this.indexList = _this.modelItems.length;
    return sel+options+selEnd;
};
Element.prototype._init = function(cfg){
    if(cfg.value) this.value = cfg.value;
    if(cfg.id) this.id = cfg.id;
    if(cfg.type) this.type = cfg.type;
    if(cfg.renderTo) this.renderTo= cfg.renderTo;
    if(cfg.handler) this.handler= cfg.handler;
    if(cfg.name) this.name= cfg.name;
    if(cfg.label) this.label= cfg.label;
    if(cfg.width) this.width= cfg.width;
    if(cfg.height) this.height= cfg.height;
    
    if(cfg.collapsed) this.collapsed= cfg.collapsed;
    if(cfg.collapsible) this.collapsible= cfg.collapsible;
    if(cfg.draggable) this.draggable= cfg.draggable;
    
    if(cfg.proxy) this.proxy= cfg.proxy;
    if(cfg.fields) this.fields= cfg.fields;
    if(cfg.change) this.change= cfg.change;
    if(cfg.dataIndex) this.dataIndex= cfg.dataIndex;
    if(cfg.dataField) this.dataField= cfg.dataField;
    
    if(cfg.title) this.title= cfg.title;
    
    
    this.isCreated = true;
}

Element.prototype.create = function(cfg){
    
    if(!this.isCreated) this._init(cfg);
    var _this = this;
    
    var eid = this.getId(this.id);
    var renderTo = this.getId(this.renderTo);
    
    if(this.renderTo!==''){
        switch(this.type){
            case "button":
                //$(renderTo).append('<div class="rck_panel_element">'+this.getLabelStringFor()+this.getButtonString()+'</div>');
                //$(renderTo).append(this.getButtonString());
                $(renderTo).append(this.getLabelStringFor());
                $(renderTo).append(this.getButtonString());
                this.addClickEvents();
                $(eid).button();
                break;
            case "label":
                $(renderTo).after(this.getLabelString());
                break;
            case "text":
                $(renderTo).append('<div class="rck_panel_element">'+this.getLabelStringFor()+this.getTextInputString()+'</div>');
             //   $(renderTo).append(this.getTextInputString());
                $(eid).button();
                break;
            case "select":
                if(this.fields.length>0){
                    $(renderTo).append('<div class="rck_panel_element">'+this.getLabelStringFor()+this.getSelectString()+'</div>');
                 //   $(renderTo).append(this.getSelectString());
                    this.addSelectEvents();
                    $(eid).combobox();
                }
                else{
                    if(_this.proxy){
                        var http = new Request();
                        http.request({
                            url:_this.proxy.url,
                            success:function(data){
                                if(_this.beforeSuccess){
                                    _this.beforeSuccess(data);
                                }
                            
                            
                                _this.fields = data.rows;
                                $(renderTo).append('<div class="rck_panel_element">'+_this.getLabelStringFor()+_this.getSelectString()+'</div>');
                               // $(renderTo).append(_this.getSelectString());
                                _this.addSelectEvents();
                                $(eid).combobox();
                            
                            
                                if(_this.afterSuccess){
                                    _this.afterSuccess(data);
                                }
                            }
                        });
                    }
                }
            break;
        }
        this.rendered = true;
    }
    return this;
};

/*
 *  Clase Panel
 *  *************************************************************************************************************************
 **/


Panel.prototype = new Element();
Panel.prototype.constructor = Panel;
function Panel(){}

Container.prototype = new Element();
Container.prototype.constructor = Container;
function Container(){}

Panel.prototype.collapsible = false;
Panel.prototype.collapsed = false;
Panel.prototype.modal = false;
Panel.prototype.draggable = false;
Panel.prototype.isInner = false;
Panel.prototype.title = '';

Panel.prototype.width = '100%';
Panel.prototype.height = '100%';

Panel.prototype.headerToolbar = [];
Panel.prototype.items = [];
Panel.prototype.buttons = [];
Panel.prototype.footerToolbar = [];

Panel.prototype.panelId = '';
Panel.prototype.buttonsPanelId = '';

Panel.prototype.setHeaderToolbar = function(){
    
    }
Panel.prototype.setItems = function(){
    
    }
Panel.prototype.setButtons = function(){
    
    }
Panel.prototype.setFooterToolbar = function(){
    
    }

Panel.prototype.setPanelActions = function(){
    var uid = this.uniqueId();
    var panelUid = uid+'-panel';
    this.buttonsPanelId = uid+'-buttons';
    
    this.panelId = panelUid;
    
    var renderTo = this.getId(this.renderTo);
    var toggleId = this.getId(uid);
    var panelId = this.getId(panelUid);
    
    var nextNode = $(renderTo).parent();
    var type = 'parent';
    
    var u = $('<ul class="rck_panel ui-panel" id="'+panelUid+'">');
    var head = '<a href="javascript:void(0);" id="'+uid+'" class="ui-dialog-title">'+this.title+'</a> ';
    
    if($(renderTo).prev()[0]){
        nextNode = $(renderTo).prev();
        type = 'next';
    }
    else{
        if($(renderTo).next()[0]){
            nextNode = $(renderTo).next();
            type='prev';
        }
    }
    
    var content = $(renderTo).html();
    
    $(u).append('<li class="rck_panel_title ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">'+head+'</li>');
    $(u).append('<li class="rck_panel_content ui-dialog-content ui-widget-content "><div  id="'+this.renderTo+'">'+content+'</div></li>');
    $(u).append('<li class="ui-dialog-content ui-widget-content"><div class="rck_panel_buttons" id="'+this.buttonsPanelId+'"></div></li>');
    
    append = '<ul style="list-style:none;padding:0;width:'+this.formatSizeStyle(this.width)+';" class="ui-dialog-titlebar ui-corner-all ui-helper-clearfix" id="'+this.panelId+'">'+$(u).html()+'</ul>';
    
    $(renderTo).replaceWith(append);
    
    if(this.collapsible){
        $(toggleId).click(function(){
            $(renderTo).toggle('slideUp');
        });
    }
    if(this.collapsed)
        $(renderTo).css('display','none');
    
    if(this.draggable)
        $(panelId).draggable();
}

Panel.prototype.create = function(cfg){
    if(!this.isCreated) this._init(cfg);
    if(cfg.items) this.items = cfg.items;
    if(cfg.buttons) this.buttons = cfg.buttons;
    
    var _this = this;
    var eid = this.getId(this.id);
    var renderTo = this.getId(this.renderTo);
    
    
    //console.log(this.renderTo);
    
    if(this.items.length>0){
        
        this.setPanelActions();
        jQuery.each(this.items, function(index,item){
            tmp = item;
            if(!(item instanceof Element)){
                switch(item.type){
                    case 'panel':
                        item.isInner = true;
                        newContentPanelUid = _this.uniqueId();
                        tmp = (new Panel()).create(item);
                        tmp.setRenderTo(newContentPanelUid);
                        
               //         console.debug(tmp);
                        
                    break;
                    default:
                        tmp = (new Element()).create(item);
                        tmp.setRenderTo(_this.renderTo);
                    break;
                }
            }
            
            tmp.render();
        });
        
        jQuery.each(this.buttons, function(index,item){
            tmp = item;
            if( !(item instanceof Element)){
                var newItem = (new Element()).create(item);
                tmp = newItem;
            }
            
            tmp.setRenderTo(_this.buttonsPanelId);
            tmp.render();
        });
        
    }
    return this;
}






/*
 *  Definicion de framework Rocket
 *  *************************************************************************************************************************
 **/


Rocket.Create = function(config){
    if(config.type!=='panel')
        return (new Element()).create(config);
    else return (new Panel()).create(config);
};